package com.example.watchimageh264

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Intent
import android.os.Build
import android.os.IBinder

class MyMediaProjectionService : Service() {
    private lateinit var pushThread: Thread

    override fun onCreate() {
        super.onCreate()
        // 创建通知渠道
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channelId = "media_projection_channel"
            val channelName = "Media Projection Service"
            val notificationChannel = NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_DEFAULT)
            val manager = getSystemService(NotificationManager::class.java)
            manager.createNotificationChannel(notificationChannel)

            val notification = Notification.Builder(this, channelId)
                .setContentTitle("Media Projection")
                .setContentText("正在采集屏幕")
                .build()

            startForeground(1, notification)
        }
        // 启动推流线程
        startPushLoop()
    }

    private fun startPushLoop() {
        pushThread = Thread {
            while (!Thread.currentThread().isInterrupted) {
                try {
                    // 这里放置你的推流逻辑（读取编码数据、发送）
                    // 例如：检测socket连接状态，断开重连
                    // 伪代码：
                    // if (!socket.isConnected()) {
                    //     socket.connect()
                    // }
                    // socket.send(data)

                    // 模拟等待
                    Thread.sleep(30)
                } catch (e: Exception) {
                    e.printStackTrace()
                    // 出现异常后，可以尝试重连
                }
            }
        }
        pushThread.start()
    }

    override fun onDestroy() {
        super.onDestroy()
        // 停止推流线程
        pushThread.interrupt()
        // 关闭socket
        // socket.close()
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        // 这里可以处理重启逻辑
        return START_STICKY
    }

    override fun onBind(intent: Intent?): IBinder? {
        return null
    }
}